<template>
	<el-card class="el-card" shadow="hover">
		<div slot="header">
		<h2>系统登录</h2>
		</div>
		<el-form :model="ruleForm" :rules="rules" ref="ruleForm">
		<el-form-item prop="account">
			<el-input v-model="ruleForm.account" clearable class="login-input" placeholder="用户名">
			<i slot="prefix" class="el-input__icon el-icon-message"></i>
			</el-input>
		</el-form-item>
		<el-form-item prop="pass">
			<el-input v-model="ruleForm.pass" clearable class="login-input" type="password" placeholder="密码">
			<i slot="prefix" class="el-input__icon el-icon-goods"></i>
			</el-input>
		</el-form-item>
		<el-form-item>
			<el-button  type="primary" class="login-button" @click="submitForm('ruleForm')">登录</el-button>
		</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
import jwtDecode from 'jwt-decode';
export default {
	data() {
		return {
			ruleForm: {
				account: "",
				pass: ""
			},
			rules: {
				account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
				pass: [{ required: true, message: "请输入密码", trigger: "blur" }]
			}
		};
	},
	methods: {
		submitForm(ruleForm) {
			var _this = this;
			this.$refs.ruleForm.validate(valid => {
				if (valid) {
					this.axios({
						method: 'post',
						url: '/api/user/login?email='+this.ruleForm.account+'&password='+this.ruleForm.pass,
						data:{
							email: this.ruleForm.account,
							password: this.ruleForm.pass
						},
						headers:{'Content-Type':'application/x-www-form-urlencoded'},
						transformRequest:[function (data) {
							let ret = ''
							for (let it in data) {
								ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
							}
								return ret
						}],
					}).then(res => {
						if(res.status === 200 && res.data.result_code ==="SUCCESS") {
							localStorage.setItem('token',res.data.data.token);
							const decoded = jwtDecode(res.data.data.token);
							this.$router.push('/gatewaytable');
						} else {
							this.$message.error('用户名或密码错误');
							return false;
						}
					}).catch(err => {
						this.$message.error('用户名或密码错误');
					})
				}else {
					this.$message.error('用户名或密码错误');
					return false;
				}
			});
		}
	}
};
</script>

<style scoped>
.el-card {
  width: 450px;
  margin: 180px auto;
}
.login-button {
  width: 410px;
  margin: 15px 0 15px 0;
}
.login-input {
  margin-top: 15px;
}
</style>

